<?php

namespace app\admin\controller;

use app\admin\facade\Qiniu;
use app\admin\model\QiniuPic as QiniuPics;
use app\admin\traits\ControllerTrait;
use app\admin\validate\QiniuPic as QiniuPicValidate;
use think\facade\Env;
use app\common\upload\QiniuUpload;

class QiniuPic extends AdminBase
{

    use ControllerTrait;
    public function initialize()
    {
        parent::initialize();
        $this->m = new QiniuPics;   //别名：避免与控制名冲突
        $this->v=new QiniuPicValidate;   //创建一个验证类
    }

    public function tree($page = 1, $limit = 10)
    {
        $count=$this->m->count();
        $data=$this->m->order('id desc')->page($page,$limit)->select();
        return json([
            'code'=>0,
            'msg'=>'查询成功',
            'count'=>$count,
            'data'=>$data
        ]);
    }
    public function add()
    {
    }
    //同步已上传的七牛云图片
    public function sync_pic(){
        //同步fetch的图片到本地
        $methods=array(
            array('prefix'=>'fetch','limit'=>1000, 'delimiter'=>'','type'=>'远程抓取'),
            array('prefix'=>'','limit'=>1000, 'delimiter'=>'/','type'=>'手动上传'),
            array('prefix'=>'news','limit'=>1000,'delimiter'=>'','type'=>'文章图片'),
            array('prefix'=>'ueditor','limit'=>1000, 'delimiter'=>'','type'=>'ueditor上传')
        );
        $domain=Env::get('qiniu.qiniu_domain');
        foreach ($methods as $method){
            Qiniu::getFiles($method['prefix'], $method['limit'],$method['delimiter'],function ($items) use ($domain,$method){
                foreach ($items as $item){
                    $qp=new QiniuPics();
                    $url=$domain.$item['key'];
                    $qnpic=$qp->where('url',$url)->find();
                    if($qnpic){//更新数据
                        $qnpic->fsize=$item['fsize'];
                        $qnpic->mime_type=$item['mimeType'];
                        $qnpic->hash=$item['hash'];
                        $qnpic->last_time=date('Y-m-d H:i:s',$item['putTime']/10000000);
                        $qnpic->save();
                    }else{//插入数据
                        $data=array(
                            'url'=>$url,
                            'title'=>QiniuUpload::getNameFromUrl($item['key'])['oriName'],
                            'type'=>$method['type'],
                            'fsize'=>$item['fsize'],
                            'last_time'=>date('Y-m-d H:i:s',$item['putTime']/10000000),
                            'mime_type'=>$item['mimeType'],
                            'hash'=>$item['hash'],
                        );
                        $qp->save($data);
                    }
                }
            });
        }
        return xjson('同步成功!');
    }
}